package com.ccf.business.knowledge.controller;

import cn.hutool.core.util.StrUtil;
import com.ccf.business.knowledge.model.vo.LabelDataVO;
import com.ccf.business.knowledge.service.ILabelDataService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ccf.business.knowledge.model.LabelData;
import com.common.model.pojo.Query;
import com.common.model.result.CodeEnum;
import com.common.model.result.PageResult;
import com.common.model.result.Result;
import com.service.websocket.to.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 标注记录
 *
 * @author ccf
 * @date 2022-02-15 16:56:10
 */
@Slf4j
@RestController
@RequestMapping("/labeldata")
@Api(tags = "标注记录相关")
@RequiredArgsConstructor
public class LabelDataController {

    private final ILabelDataService labelDataService;

    /**
     * 列表
     */
    @ApiOperation(value = "分页查询列表")
    @ApiImplicitParam(value = "任务id", name = "taskId", required = true)
    @GetMapping
    public PageResult list(Query query) {
        if (query.getParams().get("taskId") == null){
            PageResult result = new PageResult();
            result.setCode(CodeEnum.ERROR.getCode());
            result.setMsg("没有任务id");
            return result;
        }
        return labelDataService.findList(query);
    }

    /**
     * 列表
     */
    @ApiOperation(value = "分页查询标注列表")
    @ApiImplicitParam(value = "任务id", name = "taskId", required = true)
    @GetMapping("/labelList")
    public PageResult labelList(Query query) {
        if (query.getParams().get("taskId") == null){
            PageResult result = new PageResult();
            result.setCode(CodeEnum.ERROR.getCode());
            result.setMsg("没有任务id");
            return result;
        }
        return labelDataService.labelList(query);
    }

    /**
     * 列表
     */
    @ApiOperation(value = "分页查询审核列表")
    @ApiImplicitParam(value = "任务id", name = "taskId", required = true)
    @GetMapping("/auditList")
    public PageResult auditList(Query query) {
        if (query.getParams().get("taskId") == null){
            PageResult result = new PageResult();
            result.setCode(CodeEnum.ERROR.getCode());
            result.setMsg("没有任务id");
            return result;
        }
        return labelDataService.findList(query);
    }

    /**
     * 查询
     */
    @ApiOperation(value = "查询",response = LabelDataVO.class)
    @GetMapping("/{id}")
    public Result getById(@PathVariable String id) {
        User user = labelDataService.checkLocks(id);
        if (user != null ){
            return Result.failed("此数据正在被"+user.getUserName()+"操作中,请重新选择");
        }
        LabelDataVO model = labelDataService.detail(id);
        return Result.succeed(model, "查询成功");
    }

    /**
     * 判断占用
     */
    @GetMapping("/checkLock/{id}")
    @ApiOperationSupport(order = 20)
    @ApiOperation(value = "判断资源被谁占用", notes = "判断资源被谁占用")
    public Result checkLock(@PathVariable String id) {
        if (StrUtil.isBlank(id)){
            return Result.failed("id不能为空");
        }
        try {
            User locksById = labelDataService.getLocksById(id);
            if (locksById == null){
                return Result.succeed(null, "没有被占用");
            } else{
                return Result.succeed(locksById.getUserName(),String.format("资源被%s占用",locksById.getUserName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("查询出错"+e.getMessage());
        }
    }

    /**
     * 新增or更新
     */
    @ApiOperation(value = "保存")
    @PostMapping
    public Result save(@RequestBody LabelDataVO labelData) {
        labelDataService.saveAndLabel(labelData, LabelData.TAGGING);
        return Result.succeed("保存成功");
    }

    /**
     * 提交
     */
    @ApiOperation(value = "提交")
    @PostMapping("/submit")
    public Result submit(@RequestBody LabelDataVO labelData) {
        labelDataService.submit(labelData);
        return Result.succeed("提交成功");
    }

    /**
     * 提交
     */
    @ApiOperation(value = "撤回")
    @PostMapping("/recall")
    public Result recall(@RequestBody LabelData labelData) {
        labelDataService.recall(labelData);
        return Result.succeed("撤回成功");
    }

    /**
     * 提交
     */
    @ApiOperation(value = "审核提交")
    @PostMapping("/audit")
    public Result audit(@RequestBody LabelDataVO labelData) {
        labelDataService.audit(labelData);
        return Result.succeed("审核成功");
    }


    @ApiOperation(value = "全部审核通过")
    @PostMapping("/auditAll")
    @ApiImplicitParam(value = "任务id(必传)", name = "taskId", required = true)
    public Result auditAll(@RequestBody LabelDataVO labelData) {
        if (StrUtil.isBlank(labelData.getTaskId())){
            return Result.failed("taskId不能为空");
        }
        try {
            labelDataService.auditAll(labelData);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("审核失败");
        }
        return Result.succeed("审核成功");
    }

    /**
     * 下一篇
     */
    @ApiOperation(value = "下一篇（标注时）")
    @GetMapping("/next/label/{id}")
    public Result nextTag(@PathVariable String id) {
        String nextId = labelDataService.next(id, LabelData.TAGGING);
        if (nextId == null || nextId.equalsIgnoreCase(id)){
            return Result.failed("已经是最后一篇了");
        }
        return Result.succeed(nextId, "查询成功");
    }

    /**
     * 下一篇
     */
    @ApiOperation(value = "下一篇（审核时）")
    @GetMapping("/next/audit/{id}")
    public Result nextAudit(@PathVariable String id) {
        String nextId = labelDataService.next(id, LabelData.WAITING_AUDIT);
        if (nextId == null|| nextId.equalsIgnoreCase(id)){
            return Result.failed("已经是最后一篇了");
        }
        return Result.succeed(nextId, "查询成功");
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id) {
        //批量删除
        if (StrUtil.contains(id, ",")){
            String[] ids = StrUtil.split(id, ",");
            labelDataService.removeByIds(Arrays.stream(ids).collect(Collectors.toList()));
        } else {
            labelDataService.removeById(id);
        }
        return Result.succeed("删除成功");
    }
}
